<?php
/**
 * Created by PhpStorm.
 * User: lyq
 * Date: 2018/12/01
 * Time: 下午5:22
 */

namespace app\common\model;

use think\Db;
use think\Exception;

class Order extends Common
{


    /**
     * 确认订单来自购物车
     * @param $user
     * @param $data
     * @return array
     * @throws DeveloperException
     * @throws UserException
     */
    static public function carConfirmOrder($user_id, $cart_id)
    {
        $good_list = db("goods_car")->alias("a")->join("goods b", "a.goods_id=b.id")->whereIn("a.id", explode(",", $cart_id))->field("a.num cart_num, a.id cart_id, a.spec_id, b.title good_title, b.img_url, b.dispatch_type, b.dispatch_price, b.status, b.use_spec, b.id goods_id, b.price")->select();
        $send_fee = 0;
        $good_total = 0;
        $good_num = 0;
        foreach ($good_list as &$g) {
            if ($g["dispatch_type"] == 1) {
                $send_fee += $g["dispatch_price"];
            } else {
                $send_fee += $g["dispatch_price"] * $g["cart_num"];
            }
            if ($g["use_spec"] == 1) {
                $g["price"] = db("goods_spec")->where("goods_id", $g["goods_id"])->where("id", $g["spec_id"])->value("price");
            }
            $good_total += $g["price"] * $g["cart_num"];
            $good_num += $g["cart_num"];
        }
        //获取用户可用积分
        $user = User::exists($user_id);
        $order["good_list"] = $good_list;
        $order["good_total"] = $good_total;
        $order["good_num"] = $good_num;
        $order["send_fee"] = $send_fee;
        $order["total_price"] = round($good_total + $send_fee, 2);
        $order["score"] = $user["score"];
        $rate = db("rate")->find();
        if($rate["score_rate"]>0){
            //订单最大抵扣金额
            $max_discount = round($order["total_price"] * $rate["order_score_rate"] / 100);
            //所有积分最大抵扣
            $order["score_fee"] = sprintf("%.2f", $user["score"] / $rate["score_rate"]);
            if ($order["score_fee"] > $max_discount) {
                $order["score_fee"] = $max_discount;
            }
            $order["allow_score"] = floor($order["score_fee"] * $rate["score_rate"]);
        }else{
            $order["score_fee"] = 0;
            $order["allow_score"]=0;
        }
        return $order;
    }

    /**
     * 提交订单来自购物车
     */
    static public function carSubOrder($user_id, $cart_id, $name, $mobile, $address, $is_score)
    {
        $order_sn = self::generateOrderSn();
        \db("order")->startTrans();
        \db("order_goods")->startTrans();
        try {
            $good_list = db("goods_car")->alias("a")->join("goods b", "a.goods_id=b.id")->whereIn("a.id", explode(",", $cart_id))->field("a.num cart_num, a.id cart_id, a.spec_id, b.title good_title, b.img_url, b.dispatch_type, b.dispatch_price, b.status,b.stock, b.use_spec, b.id goods_id, b.price")->select();
            $send_fee = 0;
            $good_total = 0;
            $good_num = 0;
            $order_goods = [];
            $commission1 = 0;
            $commission2 = 0;
            foreach ($good_list as &$g) {
                $temp = [
                    "uid" => $user_id,
                    "goods_id" => $g["goods_id"],
                    "title" => $g["good_title"],
                    "img_url" => $g["img_url"],
                    "num" => $g["cart_num"],
                    'is_comment' => 0
                ];
                if ($g["use_spec"] == 1) {
                    if (empty($g["spec_id"])) {
                        throw new Exception($g["title"] . "规格错误");
                    }
                    $spec = db("goods_spec")->where("goods_id", $g["goods_id"])->where("id", $g["spec_id"])->find();
                    if ($spec["stock"] < $g["cart_num"]) {
                        throw new Exception($g["title"] . "库存不足");
                    }
                    $g["price"] = $spec["price"];
                    $temp["spec_id"] = $g["spec_id"];
                    $temp["spec_title"] = $spec["title"];
                    $temp["price"] = $spec["price"];
                } else {
                    if ($g["stock"] < $g["cart_num"]) {
                        throw new Exception($g["title"] . "库存不足");
                    }
                    $temp["spec_id"] = $g["spec_id"];
                    $temp["spec_title"] = "";
                    $temp["price"] = $g["price"];
                }
                $temp["order_sn"] = $order_sn;

                //计算商品佣金
                $commission = Commission::calcuteCommission($temp["goods_id"], $temp["num"], $temp["spec_id"]);
                $temp = array_merge($temp, $commission);
                if ($g["dispatch_type"] == 1) {
                    $send_fee += $g["dispatch_price"];
                } else {
                    $send_fee += $g["dispatch_price"] * $g["cart_num"];
                }
                $good_total += $g["price"] * $g["cart_num"];
                $good_num += $g["cart_num"];
                $commission1 += $temp["commission1"];
                $commission2 += $temp["commission2"];
                $order_goods[] = $temp;
            }
            //获取用户可用积分
            $user = User::exists($user_id);
            $order = [
                "order_sn" => $order_sn,
                "uid" => $user_id,
                "num" => $good_num,
                "goods_price" => $good_total,
                "dispatch_price" => $send_fee,
                "total_price" => round($good_total + $send_fee, 2),
                "send_name" => $name,
                "send_mobile" => $mobile,
                "send_address" => $address,
                "commission1" => $commission1,
                "commission2" => $commission2,
                "create_time" => time(),
                "update_time" => time()
            ];
            if ($is_score) {
                $rate = db("rate")->find();
                //订单最大抵扣金额
                $max_discount = round($order["total_price"] * $rate["order_score_rate"] / 100);
                //所有积分最大抵扣
                $order["score_fee"] = sprintf("%.2f", $user["score"] / $rate["score_rate"]);
                if ($order["score_fee"] > $max_discount) {
                    $order["score_fee"] = $max_discount;
                }
                $order["allow_score"] = floor($order["score_fee"] * $rate["score_rate"]);
                $order["money"] = $order["total_price"] - $order["score_fee"];
            } else {
                $order["money"] = $order["total_price"];
            }
            $order_id = \db("Order")->insertGetId($order);
            if (!$order_id) {
                throw new Exception("创建订单失败");
            }
            if (!\db("order_goods")->insertAll($order_goods)) {
                throw new Exception("创建订单详情失败");
            }
            //清除购物车数据
            Cart::carRemove($user_id, explode(",", $cart_id));
            if ($is_score) {
                //减少用户积分
                User::decScore($user_id, $order["allow_score"],2,$order_id);
            }
            //处理商品库存
            self::stock($good_list);
            \db("order")->commit();
            \db("order_goods")->commit();
            return $order_id;
        } catch (\Exception $e) {
            \db("order")->rollback();
            \db("order_goods")->rollback();
            throw new Exception($e->getMessage());
        }
        return $order;
    }

    /**
     * 生成订单编号
     * @return string
     */
    static public function generateOrderSn()
    {
        return date("YmdHis") . random(6, true);
    }

    /**
     * 订单商品库存处理
     * type 库存变更类型 1 售出 2 取消
     */
    public static function stock($data, $type=1)
    {
        if($type == 1){
            foreach ($data as $item) {
                if ($item["spec_id"] > 0) {
                    \db("goods_spec")->where("id", $item["spec_id"])->setDec("stock", $item["cart_num"]);
                } else {
                    \db("goods")->where("id", $item["goods_id"])->setDec("stock", $item["cart_num"]);
                }
                \db("goods")->where("id", $item["goods_id"])->setInc("sales_nums", $item["cart_num"]);
            }
        }elseif ($type == 2){
            foreach ($data as $item) {
                if ($item["spec_id"] > 0) {
                    \db("goods_spec")->where("id", $item["spec_id"])->setInc("stock", $item["num"]);
                } else {
                    \db("goods")->where("id", $item["goods_id"])->setInc("stock", $item["num"]);
                }
                \db("goods")->where("id", $item["goods_id"])->setDec("sales_nums", $item["num"]);
            }
        }
    }


    /**
     * 订单列表
     */
    static public function orderList($user_id, $type = 1, $page = 1, $page_size = 10)
    {
        $model = db("order")->where("uid", $user_id)->where("is_valid", 1);
        switch ($type) {
            case 1:
                //待付款
                $model->where("order_status", 0);
                break;
            case 2:
                //代发货，待收货
                $model->where("order_status", "in", [1,2]);
                break;
            case 3:
                //待评价，已评价
                $model->where("order_status", "in", [3,5]);
                break;
            case 4:
                //已取消
                $model->where("order_status", 4);
                break;
            default:
                throw new DeveloperException('无此订单类型');
                break;

        }
        $list = $model->limit(($page-1)*$page_size, $page_size)->select();
        foreach ($list as &$item) {
            $item['data'] = Db::name('order_goods')
                ->where('order_sn', $item['order_sn'])
                ->field('id as order_good_id,goods_id,title,img_url,spec_title,is_comment')
                ->select();
        }
        return $list;
    }


    /**
     * 取消订单
     * @param $user_id
     * @param $order_id
     * @return string
     */
    static public function orderCancel($user_id, $order_id)
    {
        $order = \db("order")->where("id", $order_id)->where("uid", $user_id)->find();
        if (empty($order)) {
            throw new UserException('无此订单！');
        }
        if ($order['order_status'] == 4) {
            throw new UserException('请不要重复取消订单！');
        }
        if ($order['pay_status'] > 0) {
            throw new UserException('已支付成功，无法取消订单！');
        }
        $data["order_status"]=4;
        //获取订单详情
        $order_goods = \db("order_goods")->where("order_sn", $order["order_sn"])->select();
        self::stock($order_goods, 2);
        //是否使用积分，如是返还积分
        if($order["allow_score"]>0){
            User::decScore($user_id, $order["allow_score"], 1, $order["id"]);
        }
        \db("order")->where("id", $order_id)->update($data);
    }


    /**
     * 订单确认收货
     * @param $uid
     * @param $order_id
     * @return string
     * @throws UserException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    static public function orderReceive($uid, $order_id, $server=0)
    {
        $where = [
            'id' => $order_id,
        ];
        if(!$server){
            $where["uid"] = $uid;
        }

        $order = Db::name('order')
            ->where($where)
            ->find();

        if (!$order) {
            throw new UserException('您的订单中无此订单记录');
        }
        if ($order['is_cancle'] != 0) {
            throw new UserException('订单已取消！');
        }
        if ($order['is_valid'] != 1) {
            throw new UserException('订单已删除！');
        }

        if ($order['order_status'] == 0) {
            throw new UserException('订单还未支付，无法确认收货');
        }
        if ($order['order_status'] == 1) {
            throw new UserException('订单还未发货，无法确认收货');
        }
        if ($order['order_status'] == 4) {
            throw new UserException('订单已取消，无法确认收货');
        }
        if ($order['order_status'] == 3 || $order['order_status'] == 5) {
            throw new UserException('订单已收货，无法重复收货');
        }
        //发放佣金
        $commission1 = $order["commission1"];
        $commission2 = $order["commission2"];
        $user = \db("user")->where("id", $order['uid'])->find();
        //查询用户上级
        if($order["commission_status"]==0){
            if(!empty($user["parent_id"])){
                $parent1 = \db("user")->where("id", $user["parent_id"])->find();
                if($parent1["in_blacklist"] == 0){
                    Commission::commissionLog($parent1["id"], $commission1, 1, "订单一级佣金", $order_id);
                    \db("user")->where("id", $parent1["id"])->setInc("commission_ready", $commission1);
                }
                if(!empty($parent1["parent_id"])){
                    $parent2 = \db("user")->where("id", $parent1["parent_id"])->find();
                    if($parent2["in_blacklist"] == 0){
                        Commission::commissionLog($parent2["id"], $commission2, 1, "订单二级佣金", $order_id);
                        \db("user")->where("id", $parent2["id"])->setInc("commission_ready", $commission2);
                    }
                }
            }
        }

        /*修改订单状态*/
        $data = [
            'commission_status' => 1,//佣金结算状态
            'order_status' => 3,
            'receive_time' => now_datetime(),
            "update_time"=>time()
        ];
        \db("order")->where("id", $order_id)->update($data);
        return '确认收货成功！';
    }


    /**
     * 订单详情
     * @param $user_id
     * @param $order_id
     * @return array
     * @throws UserException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    static public function orderInfo($order_id)
    {
        $order = \db("order")->where("id", $order_id)->find();
        if (!$order) {
            throw new UserException('无此订单！');
        }
        if ($order['is_valid'] != 1) {
            throw new UserException('订单已删除！');
        }

        switch ($order['order_status']) {
            case 0:
                $status_str = '待付款';
                $order_time = \db("rate")->value("order_time");
                $desc_str = '您的订单已提交，请在' . $order_time . '分钟内完成支付，超时订单将取消';
                $status_str_two = '待付款，请付款';
                $status_time = accurateDate($order['update_time']);
                $pay_time = '';
                break;

            case 1:
                $status_str = '待发货';
                $desc_str = '您的订单正在出库，请耐心等待';
                $status_str_two = '包裹正在出库中';
                $status_time = accurateDate($order['update_time']);
                $pay_time = accurateDate($order['pay_time']);
                break;
            case 2:
                $status_str = '发货中';
                $desc_str = '您的订单正在路上，请耐心等待';
                $status_str_two = '包裹正在路上';
                $status_time = accurateDate($order['update_time']);
                $pay_time = accurateDate($order['pay_time']);
                break;
            case 3:
                //还有未评价的商品
                $status_str = '待评价';
                $desc_str = '您的订单已完成，正在等待你的评价，赶快去评价吧';
                $status_str_two = '待评价';
                $status_time = accurateDate($order['update_time']);
                $pay_time = accurateDate($order['pay_time']);
                break;
            case 4:
                //还有未评价的商品
                $status_str = '已取消';
                $desc_str = '您的订单已取消';
                $status_str_two = '已取消';
                $status_time = accurateDate($order['update_time']);
                $pay_time = accurateDate($order['pay_time']);
                break;
            case 5:
                //还有未评价的商品
                $status_str = '待评价';
                $desc_str = '您的订单已完成，正在等待你的评价，赶快去评价吧';
                $status_str_two = '待评价';
                $status_time = accurateDate($order['update_time']);
                $pay_time = accurateDate($order['pay_time']);
                break;
            default:
                throw new UserException('订单信息有误！');
                break;
        }

        $data = Db::name('order_goods')
            ->where('order_sn', $order["order_sn"])
            ->field('id as order_goods_id,goods_id,title,img_url,spec_title,price,num,is_comment')
            ->select();
        $order["data"] = $data;
        $order["status_str"] = $status_str;
        $order["desc_str"] = $desc_str;
        $order["status_str_two"] = $status_str_two;
        $order["status_time"] = $status_time;
        $order["pay_time"] = $pay_time;
        return $order;
    }



    //TODO 以下为待使用处理

    /**
     * 删除订单 软删除
     * @param $user_id
     * @param $order_id
     * @return string
     */
    static public function orderRemove($user_id, $order_id)
    {

        $del = Db::name('order')
            ->where('id', $order_id)
            ->where('uid', $user_id)
            ->where('pay_status >= 3 OR is_CANCLE = 1')
            ->update(['is_valid' => 0]);
        if ($del) {
            return '订单删除成功！';
        } else {
            throw new UserException('仅可删除已完成或已取消的订单！');
        }
    }




    /**
     * 订单评价
     * @param $user_id
     * @param $order_goods_id
     * @param $star
     * @param $content
     * @return string
     * @throws UserException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    static public function orderComment($user_id, $order_goods_id, $star, $content)
    {

        $order_goods = Db::name('order_goods')
            ->alias('og')
            ->join('__ORDER__ o', 'o.order_sn=og.order_sn')
            ->where('og.id', $order_goods_id)
            ->where('og.uid', $user_id)
            ->field('og.*,o.order_status, o.id order_id')
            ->find();

        $star = intval($star);
        if (empty($star) || $star > 5) {
            throw new UserException('评分只能1-5星！');
        }

        $content = remove_all_tags($content);
        if (empty($content)) {
            throw new UserException('请输入评价内容！');
        }

        if (!$order_goods) {
            throw new  UserException('您的订单中无此购买记录，无法评价！');
        }
        if ($order_goods['is_comment'] == 1) {
            throw new  UserException('此商品已评价，请不要重复评价！');
        }
        if ($order_goods['order_status'] != 3) {
            throw new  UserException('还未确认收货，无法评价！');
        }

        $data = [
            'uid' => $user_id,
            'order_id' => $order_goods['order_id'],
            'goods_id' => $order_goods['goods_id'],
            'spec_id' => $order_goods['spec_id'],
            'spec_title' => $order_goods['spec_title'],
            'star' => $star,
            'content' => $content,
            'comment_time' => now_datetime()
        ];
        Db::name('goods_comment')->insert($data);
        Db::name('order_goods')->where('id', $order_goods_id)->update(['is_comment' => 1]);
        db("order")->where("id", $data["order_id"])->update(["is_comment"=>1, "order_status"=>5]);
        //重置订单评分
        $comment_star = db("goods_comment")->where("goods_id", $data["goods_id"])->avg("star");
        \db("goods")->where("id", $data["goods_id"])->update(["comment"=>$comment_star]);
        return '评价提交成功！';
    }

}

